package com.wchat.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.List;

public class HttpUtil {
    public static String post(String url, List<NameValuePair> nvps) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        return executeRequest(httpPost);
    }

    public static String get(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        return executeRequest(httpGet);
    }

    public static class UrlBuilder {
        private StringBuilder builder;

        public UrlBuilder(String url) {
            builder = new StringBuilder(url).append('?');
        }

        public UrlBuilder setParam(String name, String value) {
            builder.append(name)
                    .append('=')
                    .append(value)
                    .append('&');
            return this;
        }

        public String build(){
            return builder.toString();
        }
    }

    private static String executeRequest(HttpUriRequest request) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request);
        try {
            StatusLine statusLine = response.getStatusLine();
            System.out.println(statusLine);
            HttpEntity entity = response.getEntity();
            System.out.println(entity);
            if (statusLine.getStatusCode() == 200) {
                return EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            throw new HttpException(statusLine.toString());
        } finally {
            if (response != null)
                response.close();
        }

    }


}
